// AdminLogServiceImpl.java
package com.easy.service.impl;

import com.easy.bean.AdminLog;
import com.easy.service.AdminLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

@Service
public class AdminLogServiceImpl implements AdminLogService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void saveLog(AdminLog adminLog) {
        String sql = "INSERT INTO admin_log (admin_id, action_type, target_table, target_id, ip_address, action_time, action_details, deleted_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";

        try {
            jdbcTemplate.execute(sql, new PreparedStatementCallback<Object>() {
                @Override
                public Object doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
                    ps.setString(1, adminLog.getAdminId() != null ? adminLog.getAdminId() : "");
                    ps.setString(2, adminLog.getActionType() != null ? adminLog.getActionType() : "");
                    ps.setString(3, adminLog.getTargetTable());
                    ps.setString(4, adminLog.getTargetId());
                    ps.setString(5, adminLog.getIpAddress());
                    ps.setObject(6, adminLog.getActionTime() != null ? adminLog.getActionTime() : new Date());
                    ps.setString(7, adminLog.getActionDetails());
                    ps.setInt(8, adminLog.getDeletedAt() != null ? adminLog.getDeletedAt() : 0);
                    return ps.executeUpdate();
                }
            });
        } catch (Exception e) {
            System.err.println("保存日志到数据库失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
